<?php

namespace App\V3\V3_2_6\Models;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class LogPackageModel extends Model
{


    use HasFactory;

    protected $table = 'log_package';

    protected $dates = [
        'out_storage_time'
    ];

    protected $dateFormat = 'U';//这个时间字段被为被格式化为UNIX 时间戳的形式存储
    //toArray 时间转换问题
    public static function outLogExport($packageId)
    {
        return LogPackageModel::select(
            'a.id',
            'a.package_name',
            'a.num',
            'a.remark',
            'a.is_cancel',
            'a.created_at',
            'username',
            'nickname',
            'out_storage_time'
        )
            ->from('log_package as a')
            ->leftJoin('admin as b', 'b.id', '=', 'a.user_id')
            ->with('hasManyContent', function($query) {
                $query->select(
                    'log_package_content.*',
                    'a.shelf_name',
                    'b.location_name',
                    'c.batch_no',
                    'd.materiel_img'
                )
                    ->leftJoin('storage_shelf as a', 'a.id', '=', 'log_package_content.shelf_id')
                    ->leftJoin('storage_shelf_location as b', 'b.id', '=', 'log_package_content.location_id')
                    ->leftJoin('storage_batch as c', 'c.id', '=', 'log_package_content.storage_batch_id')
                    ->leftJoin('materiel_type as d', 'd.id', '=', 'log_package_content.materiel_type_id');
            })->orderBy('a.id', 'desc')
            ->whereIn('a.id', $packageId)
            ->get()->toArray();
    }

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function hasManyContent()
    {
        return self::hasMany(LogPackageContentModel::class, 'log_package_id', 'id');
    }

    //今日套餐总数
    static public function getTodayPackageCount($condition, $startTime, $endTime)
    {
        return self::where($condition)
            ->whereBetween('created_at', [$startTime, $endTime])
            ->count();
    }
}
